import {
  PrimaryGeneratedColumn,
  Column,
  Entity,
  CreateDateColumn,
  UpdateDateColumn,
  BeforeInsert,
  BeforeUpdate,
  OneToOne,
  JoinColumn,
  OneToMany,
  ManyToOne,
} from 'typeorm'
import { hashSync } from 'bcryptjs'
import { ArticleEntity } from './article.entity'
import { BaseEntity } from './base.entity'
import { ProvinceEntity } from './province.entity'

@Entity('user')
export class UserEntity {
  @PrimaryGeneratedColumn()
  public id: number
  @Column({
    unique: true,
  })
  username: string

  @Column('varchar', {
    comment: '微信用户ID',
    unique: true,
  })
  wxOpenid: string

  @Column({})
  nickName: string

  @Column({
    unique: true,
  })
  phone: string

  @Column({})
  avator: string

  @Column('varchar', {
    select: false,
    comment: '密码',
  })
  password: string

  @OneToMany(
    type => ArticleEntity,
    article => article.user,
  )
  @JoinColumn()
  articles: ArticleEntity[]

  @CreateDateColumn({ comment: '创建时间', type: 'timestamp' }) // 自动生成列
  createdAt: string

  @UpdateDateColumn({ comment: '更新时间', type: 'timestamp' }) // 自动生成并自动更新列
  updatedAt: string

  @BeforeInsert()
  @BeforeUpdate()
  beforeInsert(): void {
    this.password = hashSync(this.password, 10)
  }
}

// 用户收货地址
@Entity('user_address', {})
export class UserAddressEntity extends BaseEntity {
  @ManyToOne(
    () => UserEntity,
    userEntity => userEntity.id,
  )
  user: UserEntity

  @Column({
    comment: '省code',
  })
  @ManyToOne(
    () => ProvinceEntity,
    provinceEntity => provinceEntity.code,
  )
  @JoinColumn({
    name: 'province_code',
    referencedColumnName: 'code',
  })
  province_code

  province_name

  @Column({
    comment: '市code',
  })
  @ManyToOne(
    () => ProvinceEntity,
    city => city.code,
  )
  @JoinColumn({
    name: 'city_code',
    referencedColumnName: 'code',
  })
  city_code

  city_name

  @Column({
    comment: '区县code',
  })
  @ManyToOne(
    () => ProvinceEntity,
    country => country.code,
  )
  @JoinColumn({
    name: 'country_code',
    referencedColumnName: 'code',
  })
  country_code

  country_name

  @Column({
    comment: '详细地址',
  })
  address: string

  @Column({
    comment: '收货人姓名',
  })
  name: string

  @Column({
    comment: '手机号',
  })
  phone: string

  @Column({
    comment: '是否默认地址',
    default: false
  })
  isDefault: boolean
}
